package br.com.ximp.ruellia;

import java.io.IOException;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.PreviewCallback;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;

public class RuelliaActivity extends Activity {
	private static final String TAG = "RuelliaActivity";

	private SurfaceView preview = null;
	private SurfaceHolder previewHolder = null;
	private Camera camera = null;
	private ImageView img = null;
	
	SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
		
		private int format;
		private int height;
		private int width;

		public void surfaceChanged(SurfaceHolder holder, int format, int width,
				int height) {
			this.width = width;
			this.height = height;
			this.format = format;
			Log.d(TAG,"surfaceChanged w="+width+" h="+height+" f="+format);
			Camera.Parameters parameters = camera.getParameters();
			parameters.setPreviewSize(width, height);
			camera.setParameters(parameters);
			camera.startPreview();
		}

		public void surfaceCreated(SurfaceHolder holder) {
			camera = Camera.open();
			camera.setPreviewCallback(new PreviewCallback() {				
				byte[] newdata;
				
				public void onPreviewFrame(byte[] data, Camera camera) {
					Log.d(TAG, "onPreviewFrame "+data.length);
					newdata = new byte[data.length];
					System.arraycopy(data, 0, newdata, 0, data.length);
					//transform to black-and-white
					for(int i=width*height+1;i<data.length;i++){
						newdata[1]=0;
					}
					Bitmap bmp = BitmapFactory.decodeByteArray(newdata,0,data.length);
					img.setImageBitmap(bmp);
				}
			});
			try {
				camera.setPreviewDisplay(previewHolder);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
			if(camera != null){
				camera.stopPreview();
				camera = null;
			}
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		img = (ImageView) findViewById(R.id.image);
		preview = (SurfaceView) findViewById(R.id.preview);
		previewHolder = preview.getHolder();
		previewHolder.addCallback(surfaceCallback);
		previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

}
